package com.pei.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pei.util.JSONFileUtils;
import com.pei.util.Resource;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
@Controller
public class FileController {
    @RequestMapping("fu")
    public String file(){
        return "fileupload";
    }

    @RequestMapping("fileUpLoad")
    public String fileUpliad(MultipartFile[] files, HttpServletRequest request) throws Exception{
        String path = request.getServletContext().getRealPath("/")+"/WEB-INF/files/";
        ObjectMapper mapper = new ObjectMapper();
        if (files != null && files.length>0){
            for (MultipartFile f : files) {
                String filename = f.getOriginalFilename();
                ArrayList<Resource> list = new ArrayList<>();
                String json = JSONFileUtils.readFile(path+"/files.json");
                if (json.length()!=0){
                    list = mapper.readValue(json, new TypeReference<ArrayList<Resource>>() {
                    });
                    for (Resource r : list) {
                        if(filename.equals(r.getName())){
                            String[] split = filename.split("\\.");
                            filename = split[0]+"(1)."+split[1];
                        }
                    }
                }
                String filePath  = path + filename;
                f.transferTo(new File(filePath));
                list.add(new Resource(filename));
                json = mapper.writeValueAsString(list);
                JSONFileUtils.writeFile(json,path+ "/files.json");
            }
            request.setAttribute("msg","(上传成功)");
            return "fileupload";

        }
        request.setAttribute("msg","(上传失败)");
        return "fileupload";

    }

    @ResponseBody
    @RequestMapping(value = "/getFilesName",produces = "text/html;charset = utf-8")
    public String getFilesName(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String path = request.getServletContext().getRealPath("/")+"/WEB-INF/files/files.json";
        String json = JSONFileUtils.readFile(path);
        return json;
    }
    public String getFilesName(HttpServletRequest request, String filename) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String agent = request.getHeader("User-Agent");
        if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = "=?UTF-8?B?" + new String(base64Encoder.encode(filename.getBytes("UTF-8"))) + "?=";
        } else {
            filename = URLEncoder.encode(filename, "UTF-8");        // IE及其他浏览器
        }
        return filename;
    }

    @RequestMapping("download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws Exception{
        String path = request.getServletContext().getRealPath("/WEB-INF/files/");
        filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8");
        File file = new File(path+File.separator+filename);
        HttpHeaders headers = new HttpHeaders();
        filename = this.getFilesName(request,filename);
        headers.setContentDispositionFormData("attachment",filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }



}
